import config from '@/utils/config.js';

var token = config.fir.token ? config.fir.token : '';
var appid = config.fir.appid ? config.fir.appid : '';

const base = 'http://api.bq04.com/apps/';
var version = 0;
var removteInfo = {};

// #ifdef APP-PLUS
plus.runtime.getProperty(plus.runtime.appid, (resp) => {
	version = resp.versionCode;
})
// #endif

const getInstallUrl = function() {
	return 'http://download.bq04.com/apps/' + appid + "/install?download_token=";
};

/**
 * 获取app
 */
const getApp = function() {
	return base + appid;
}

/**
 * 获取最后一个版本信息
 */
const getLatest = function() {
	return base + 'latest/' + appid + '?api_token=' + token + '&type=android';
}

/**
 * @param {Object} message
 * @param {Object} time
 */
const error = function(message, time) {
	time = parseInt(time);
	if (isNaN(time) || time < 1000) {
		time = 3000;
	}
	if (message) {
		uni.showToast({
			title: message,
			mask: false,
			duration: time,
			icon: "none"
		})
	}
}

// 下载更新
const install = function() {

	// #ifdef APP-PLUS
	uni.showLoading({
		title: '正在下载...'
	});

	uni.request({
		url: getApp() + '/download_token?api_token=' + token,
		method: 'GET',
		data: {},
		success: resp => {
			var down_token = resp.data.download_token;
			if (down_token === undefined) {
				error('获取download_token失败');
			} else {
				var install_url = getInstallUrl() + down_token;
				var dtask = plus.downloader.createDownload(install_url, {}, function(d, status) {
					uni.hideLoading();
					// 下载完成  
					if (status == 200) {
						plus.runtime.install(plus.io.convertLocalFileSystemURL(d
							.filename), {}, {}, function(error) {
							error('更新失败！请手动下载安装');
						})
					} else {
						error('下载文件失败！请手动下载安装');
						return false;
					}
				});
				dtask.start();
			}
		},
		fail: () => {
			error('获取download_token失败');
		},
	});
	return false;
	// #endif

	//检测当前平台，如果是安卓则启动安卓更新  
	error('自动更新仅支持安卓系统');
}

/**
 * 下载更新
 */
const request = function(callback) {
	// #ifdef APP-PLUS
	uni.request({
		url: getLatest(),
		method: 'GET',
		data: {},
		success: resp => {
			if (resp && resp.data !== undefined) {
				removteInfo = resp.data;
			}
		},
		fail: () => {

		},
		complete: () => {
			if (typeof callback === "function") {
				callback(removteInfo);
			}
		}
	});
	// #endif
}

class AppVersion {

	constructor(app_id) {
		if (app_id) {
			appid = app_id;
		}
		this.newVersion = '已是最新版';
		this.verifyFail = '自动检测版本失败，为了保证业务逻辑保存一次，请联系小马哥处理';
	}

	/**
	 * @param {Object} message
	 */
	setNewVersion(message) {
		this.newVersion = message;
	}

	/**
	 * @param {Object} message
	 */
	setVerifyFail(message) {
		this.verifyFail = message;
	}

	/**
	 * @param {Object} mode
	 */
	request(mode) {

		mode = mode === undefined ? 'modal' : mode;

		// #ifdef APP-PLUS
		uni.request({
			url: getLatest(),
			method: 'GET',
			data: {},
			success: resp => {
				if (resp && resp.data !== undefined) {
					removteInfo = resp.data;
				}

				console.log(resp);
				return false;
				var last_version = resp.data.version;
				if (last_version === undefined) {
					if (typeof this.verifyFail === "function") {
						this.verifyFail(resp);
					} else {
						uni.showToast({
							title: this.verifyFail,
							mask: false,
							duration: 3000,
							icon: "none"
						});
					}
					return false;
				}

				var content = '检测到新版本' + resp.data.versionShort + ',是否更新?';
				if (last_version > version) {
					if (mode === 'modal') {
						uni.showModal({
							title: '新版本检测',
							content: content,
							cancelText: '忽略',
							confirmText: '更新',
							success: function(resp) {
								if (resp.confirm) {
									update();
								}
							}
						})
					} else {
						if (typeof mode === "string") {
							uni.showModal({
								title: '新版本检测',
								content: content,
								cancelText: '忽略',
								confirmText: '更新',
								success: function(resp) {
									if (resp.confirm) {
										uni.navigateTo({
											url: mode,
											fail() {
												uni.switchTab({
													url: mode,
												})
											}
										})
									}
								}
							})
						} else if (typeof mode === "function") {
							mode(resp);
						}
					}
				} else {
					if (mode === 'modal') {
						if (typeof this.verifyFail === "function") {
							this.newVersion(resp);
						} else {
							uni.showToast({
								title: this.newVersion,
								mask: false,
								duration: 3000,
								icon: "none"
							});
						}
					}
				}
				return false;
			},
			fail: () => {},
			complete: () => {}
		});
		// #endif

		// #ifdef H5
		//检测当前平台，如果是安卓则启动安卓更新
		error('自动更新仅支持安卓系统');
		// #endif
	}

	// 弹出框
	modal() {

		console.log('123123');

		this.request(resp => {
			console.log(resp);
		});
	}

	/**
	 * 挂载版本信息管理器中
	 * @param {Object} vm
	 */
	mount(vm) {
		// #ifdef APP-PLUS
		plus.runtime.getProperty(plus.runtime.appid, resp => {
			// resp的值就是data的值
			var data = {
				"appid": "HBuilder",
				"version": "1.0.0",
				"name": "应用样例",
				"versionCode": "100",
				"description": "app基础开发应用样例",
				"author": "",
				"email": "",
				"features": ["uninview"]
			};
			vm.$store.commit('setVersion', resp);
		})
		// #endif

		// #ifdef MP-WEIXIN
		const data = wx.getAccountInfoSync();
		vm.$store.commit('setVersion', data);
		// #endif

		// #ifdef H5
		vm.$store.commit('setVersion', {});
		// #endif
	}

	// 挂载远程数据到状态管理器中
	remote(vm) {
		request(function(resp) {
			if (resp.version !== undefined) {
				vm.$store.commit('setRemoteVersion', resp);
			}
		});
	}

	// 检测版本
	check(callback) {
		request(function(resp) {
			if (typeof callback === "function") {
				callback(resp);
			}
		});
	}

	// 下载安装
	install() {
		install();
	}
};

/**
 * fir请求返回值
 */
const fir = {
	"data": {
		"name": "应用样例",
		"version": "100",
		"changelog": "应用样例",
		"updated_at": 1618801230,
		"versionShort": "1.0.0",
		"build": "100",
		"installUrl": "https://download.jappstore.com/apps/607cf23ab2eb464305120c0d/install?download_token=02d9a9a50a4c6d0c71ca09b6d8168ebe&source=update",
		"install_url": "https://download.jappstore.com/apps/607cf23ab2eb464305120c0d/install?download_token=02d9a9a50a4c6d0c71ca09b6d8168ebe&source=update",
		"direct_install_url": "https://download.jappstore.com/apps/607cf23ab2eb464305120c0d/install?download_token=02d9a9a50a4c6d0c71ca09b6d8168ebe&source=update",
		"update_url": "http://jappstore.com/e1c6",
		"binary": {
			"fsize": 17031304
		}
	},
	"statusCode": 200,
	"header": {
		"X-XSS-Protection": "1; mode=block",
		"Content-Length": "658",
		"X-Swift-SaveTime": "Tue, 20 Apr 2021 06:15:21 GMT",
		"Vary": "Origin",
		"Cache-Control": "max-age=0, private, must-revalidate",
		"Timing-Allow-Origin": "*",
		"Ali-Swift-Global-Savetime": "1618899321",
		"X-Frame-Options": "SAMEORIGIN",
		"Via": "cache3.l2cn3013[37,200-0,M], cache25.l2cn3013[38,0], vcache19.cn2956[125,125,200-0,M], vcache25.cn2956[127,0]",
		"ETag": "W/\"b89e097498a305cc7f51895355e8a655\"",
		"Server": "Tengine",
		"X-Swift-CacheTime": "0",
		"X-Runtime": "0.017144",
		"Date": "Tue, 20 Apr 2021 06:15:21 GMT",
		"X-Request-Id": "b1a57ff8-b76a-4928-a475-14c835ed0b34",
		"Connection": "keep-alive",
		"Content-Type": "application/json; charset=utf-8",
		"X-Content-Type-Options": "nosniff",
		"EagleId": "7d4da02d16188993211082752e",
		"Remote-Port": "4152",
		"X-Cache": "MISS TCP_MISS dirn:-2:-2"
	},
	"errMsg": "request:ok",
	"cookies": []
};

export default AppVersion;
